/*
'  DotNetNuke -  http://www.dotnetnuke.com
'  Copyright (c) 2002-2011
'  by DotNetNuke Corporation
' 
'  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
'  documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
'  the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
'  to permit persons to whom the Software is furnished to do so, subject to the following conditions:
' 
'  The above copyright notice and this permission notice shall be included in all copies or substantial portions 
'  of the Software.
' 
'  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
'  TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
'  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
'  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
'  DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Lists;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Security.Roles;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.UI.WebControls;
using DotNetNuke.Modules.Store.Providers;

namespace DotNetNuke.Modules.Store.Providers.Address.DefaultAddressProvider
{
	/// <summary>
	/// Summary description for CoreProfile.
	/// </summary>
	public partial class DefaultAddressProfile : ProviderControlBase
	{
		#region Controls

		//protected Address.DefaultAddressProvider.StoreAddress addressEdit;
		
		#endregion

		#region Private Declarations

		private AddressNavigation addressNav = null;
		private int addressId;
        private string _addressDefaultDescription;
		
		#endregion

		#region Web Form Designer generated code

		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.grdAddresses.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.grdAddresses_ItemDataBound);
		}

		#endregion

		#region Event Handlers

		protected void Page_Load(object sender, System.EventArgs e)
		{
			try 
			{
                // Get localized default address description
                _addressDefaultDescription = Localization.GetString("AddressDefaultDescription", this.LocalResourceFile);
				// Get the navigation settings and AddressID
				addressNav = new AddressNavigation(Request.QueryString);
                addressId = addressNav.AddressID;
                // Get an Address controler
			    AddressController controller = new AddressController();

				// Edit Address
				if (addressId > 0)
				{
					plhGrid.Visible = false;
					plhEditAddress.Visible = true;

					AddressInfo address = (AddressInfo)controller.GetAddress(addressId);
                    bool authorizedUser = (address.UserID == UserId);

                    if (address != null && authorizedUser == true)
                    {
                        if (string.IsNullOrEmpty(address.Email) == true)
                            address.Email = UserInfo.Email;
                        addressEdit.AddressInfo = address;
                        addressEdit.ShowUserSaved = false;
                        addressEdit.ShowPrimary = true;
                        addressEdit.ShowDescription = true;
                        addressEdit.PopulateAddress();
					    // Set delete confirmation
					    cmdDelete.Attributes.Add("onClick", "javascript:return confirm('" + Localization.GetString("DeleteItem") + "');");
                        cmdDelete.Visible = true;
                    }
                    else
                    {
                        errorMessage = Localization.GetString("ErrorLoading", this.LocalResourceFile);
                        if (authorizedUser == false)
                        {
                            // Someone is trying to steal an address!
                            // A log entry will be added in the parent control
                            invokeSecurityProviderError();
                        }
                        else
                            invokeProviderError();
                    }
				}
				// Add Address
				else if (addressId == 0)
				{
					plhGrid.Visible = false;
					plhEditAddress.Visible = true;
                    addressEdit.ShowUserSaved = false;
                    addressEdit.ShowPrimary = true;
                    addressEdit.ShowDescription = true;
                    this.addressEdit.PopulateAddress();
				}
				// Display user's addresses
				else
				{
                    List<AddressInfo> addresses = controller.GetAddresses<AddressInfo>(this.PortalId, this.UserId, _addressDefaultDescription);

				    if (addresses.Count > 0)
				    {
					    grdAddresses.DataSource = addresses;
					    grdAddresses.DataBind();
				    }

					plhGrid.Visible = true;
					plhEditAddress.Visible = false;
				}
			} 
			catch(Exception ex) 
			{
				Exceptions.ProcessModuleLoadException(this, ex);
			}
		}

		private void grdAddresses_ItemDataBound(object sender, DataGridItemEventArgs e)
		{
			IAddressInfo addressInfo = (IAddressInfo)e.Item.DataItem;

			Image imgPrimary = (Image)e.Item.FindControl("imgPrimary");
			if (imgPrimary != null)
			{
				if (addressInfo.PrimaryAddress)
					imgPrimary.Visible = true;
				else
					imgPrimary.Visible = false;
			}

			HyperLink lnkEdit = (HyperLink)e.Item.FindControl("lnkEdit");
			if (lnkEdit != null)
			{
				if (addressInfo.AddressID == 0)
				{
					//This is the registration address, so the profile editor should be used to modify this address
                    string[] urlparams = {"UserId=" + UserId.ToString()};
                    lnkEdit.NavigateUrl = DotNetNuke.Common.Globals.NavigateURL(PortalSettings.UserTabId, "Profile", urlparams);
				}
				else 
				{
					addressNav.AddressID = addressInfo.AddressID;
					lnkEdit.NavigateUrl = addressNav.GetNavigationUrl();
				}
			}
		}

		protected void btnAdd_Click(object sender, EventArgs e)
		{
			addressNav.AddressID = 0;
			Response.Redirect(addressNav.GetNavigationUrl(), false);
		}

		protected void cmdUpdate_Click(object sender, EventArgs e)
		{
			try 
			{
				if (Page.IsValid == true) 
				{
					IAddressInfo address = addressEdit.AddressInfo;

					address.AddressID = addressId;
					address.PortalID = PortalId;
					address.UserID = UserId;
					address.CreatedByUser = UserId.ToString();
					address.CreatedDate	= DateTime.Now;

					AddressController controller = new AddressController();

					if (address.AddressID > 0)
					    controller.UpdateAddress(address);
					else 
						controller.AddAddress(address);

					invokeEditComplete();

                    if (addressNav.ReturnTo != Null.NullString)
                    {
                        addressNav.PageID = addressNav.ReturnTo;
                        addressNav.ReturnTo = Null.NullString;
                        HttpContext.Current.Response.Redirect(addressNav.GetNavigationUrl(), true);
                    }
				}
			} 
			catch(Exception ex) 
			{
				Exceptions.ProcessModuleLoadException(this, ex);
			}
		}

		protected void cmdCancel_Click(object sender, EventArgs e)
		{
			try 
			{
				addressNav.AddressID = Null.NullInteger;
				invokeEditComplete();

                if (addressNav.ReturnTo != Null.NullString)
                {
                    addressNav.PageID = addressNav.ReturnTo;
                    addressNav.ReturnTo = Null.NullString;
                    HttpContext.Current.Response.Redirect(addressNav.GetNavigationUrl(), true);
                }
            } 
			catch(Exception ex) 
			{
				Exceptions.ProcessModuleLoadException(this, ex);
			}
		}

		protected void cmdDelete_Click(object sender, EventArgs e)
		{
			try 
			{
				if (addressId > 0) 
				{
					AddressController controller = new AddressController();
					controller.DeleteAddress(addressId);

					addressNav.AddressID = Null.NullInteger;
				}

				invokeEditComplete();
			} 
			catch(Exception ex) 
			{
				Exceptions.ProcessModuleLoadException(this, ex);
			}
		}

		#endregion
	}
}
